package ChatDemo.rpc.handler;

import ChatDemo.message.RpcResponseMessage;
import com.sun.applet2.AppletParameters;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ChannelHandler.Sharable
public class RpcResponseMessageHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {
    //                      序号      用来接收结果的promise对象
    public static final Map<Integer, Promise<Object>> PROMISEs=new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponseMessage msg) throws Exception {
        System.out.println(msg);
        //拿到对应的promise对象，并从map中删除
        Promise<Object> promise = PROMISEs.remove(msg.getSequenceId());
        if (promise!=null){
            Exception exceptionValue = msg.getExceptionValue();
            if (exceptionValue!=null){
                promise.setFailure(new Exception(exceptionValue));
            }else {
                promise.setSuccess(msg.getReturnValue());
            }
        }
    }
}
